package com.sks.service.privilege.impl;

import java.io.Serializable;
import javax.annotation.Resource;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import com.sks.bean.pojo.Users;
import com.sks.bean.privilege.Employee;
import com.sks.dao.privilege.UsersDao;
import com.sks.service.base.BaseService;
import com.sks.service.privilege.UsersService;
import com.sks.utils.MD5;

@Service
public class UsersServiceBean extends BaseService<Users> implements UsersService {
	
	private UsersDao usersDao ;
	
	public UsersDao getUsersDao() {
		return usersDao;
	}
	
	@Resource(name="usersDao")
	public void setUsersDao(UsersDao usersDao) {
		this.usersDao = usersDao;
		this.setDao(usersDao);
	}

	/* (非 Javadoc)
	* <p>Title: exist</p>
	* <p>Description: 根据loginName判断登录名是否存在</p>
	* @param loginName
	* @return
	* @see com.sks.service.privilege.UsersService#exist(java.lang.String)
	*/
	public boolean exist(String loginName){
		return usersDao.exist(loginName);
	}
	
	/* (非 Javadoc)
	* <p>Title: validate</p>
	* <p>Description: 根据loginName,loginPwd判断外部用户是否存在</p>
	* @param username
	* @param password
	* @return
	* @see com.sks.service.privilege.UsersService#validate(java.lang.String, java.lang.String)
	*/
	public boolean validate(String loginName, String loginPwd){
		loginPwd = MD5.MD5Encode(loginPwd);
		return usersDao.validate(loginName, loginPwd);
		
	}
	
	private void visible(boolean visible, Serializable ... entityIds){
		if(entityIds!=null && entityIds.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0; i<entityIds.length;i++){
				jpql.append('?').append(i+2).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			usersDao.visible(visible, jpql, entityIds);
		}
	}
	
	/**
	* @Title: enable
	* @Description: TODO(根据visible的值true or false  来设启用或禁用该外部用户)
	* @param @param visible
	* @param @param entityIds    设定文件
	* @return void    返回类型
	* @throws
	*/
	public void enable(boolean visible, Serializable ... entityIds) {
		visible(visible, entityIds);
	}
	
	@Override
	public void save(Users entity) {
		entity.setLoginPwd(MD5.MD5Encode(entity.getLoginPwd()));
		usersDao.save(entity);
	}
	
	/**
	* @Title: find the entity of users by loginName
	* @Description: TODO(查找外部用户的详细信息)
	* @param @param loginName 登陆名
	* @return Users    返回类型
	* @throws
	*/
	public Users findByLoginName(String loginName) {
		return usersDao.findByLoginName(loginName);
	}
	
	public void updatePassword(String loginName, String newpassword){
		newpassword = MD5.MD5Encode(newpassword);
		usersDao.updatePassword(loginName, newpassword);
	}
}
